package com.sanjin.convert;

import com.sanjin.entity.Admin;
import com.sanjin.form.AdminForm;
import com.sanjin.service.AdminService;
import com.sanjin.vo.AdminVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: sanjin
 * @date: 2019/5/7 19:41
 */
@Component
public class AdminConvert {

    @Autowired
    private AdminService adminService;

    public AdminVo admin2AdminVo(Admin admin) {
        AdminVo adminVo = new AdminVo();
        BeanUtils.copyProperties(admin, adminVo);
        return adminVo;
    }

    public List<AdminVo> admin2AdminVo(List<Admin> admins) {
        List<AdminVo> adminVos = admins.stream().map(admin -> {
            AdminVo adminVo = new AdminVo();
            BeanUtils.copyProperties(admin, adminVo);
            return adminVo;
        }).collect(Collectors.toList());
        return adminVos;
    }

    public Admin adminForm2Admin(AdminForm adminForm) {
        Admin admin = new Admin();
        // 需要对 create/update 表单分别进行处理
        if (adminForm.getPassword() == null) {
            // update form
            Admin queryAdminById = adminService.queryAdminById(adminForm.getId());
            BeanUtils.copyProperties(adminForm, admin);
            // 重新定义password
            admin.setPassword(queryAdminById.getPassword());

        } else {
            // create form
            BeanUtils.copyProperties(adminForm, admin);
        }
        return admin;
    }
}
